package jst.householdmanager.activities;

import java.util.ArrayList;

import jst.householdmanager.R;
import jst.householdmanager.database.ItemCategoriesDataSource;
import jst.householdmanager.database.ItemsDataSource;
import jst.householdmanager.database.Items_in_ItemCategoriesDataSource;
import jst.householdmanager.database.ShopsDataSource;
import jst.householdmanager.database.Shops_has_ItemsDataSource;
import jst.householdmanager.database.table.ItemCategories;
import jst.householdmanager.database.table.Items;
import jst.householdmanager.database.table.Items_in_ItemCategories;
import jst.householdmanager.database.table.Shops;
import jst.householdmanager.database.table.Shops_has_Items;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class EditItemAct extends Activity implements ListEntryCheckListener {

	private int selectedItemId = -1;
	private ArrayList<ListEntryCheck.EntryRecord> itemCategories;
	private ArrayList<ListEntryCheck.EntryRecord> shops;

	private static final int CHECKLIST_ITEMCAT = 10;
	private static final int CHECKLIST_SHOPS = 20;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_edit_item);

		EditText edt_name = ((EditText) findViewById(R.id.edit_shop_edt_name));
		EditText edt_desc = ((EditText) findViewById(R.id.edit_item_edt_desc));

		Bundle givenData = getIntent().getExtras();

		if (givenData != null) {
			this.selectedItemId = givenData.getInt("ItemId");

			Items selectedItem = ItemsDataSource.read(this.selectedItemId);

			edt_name.setText(selectedItem.getName());
			edt_desc.setText(selectedItem.getDescription());
		}

		getActionBar().setDisplayHomeAsUpEnabled(true);

		// itemcategories
		ListEntryCheck listEntryCheck_itemCat = new ListEntryCheck(EditItemAct.CHECKLIST_ITEMCAT, this);
		this.itemCategories = new ArrayList<ListEntryCheck.EntryRecord>();
		for (ItemCategories itemCategory : ItemCategoriesDataSource.readAll()) {
			boolean checked = false;
			if (this.selectedItemId != -1) {
				if (Items_in_ItemCategoriesDataSource.read(itemCategory.getId(), this.selectedItemId) != null) {
					checked = true;
				}
			}
			this.itemCategories.add(listEntryCheck_itemCat.Record(itemCategory.getId(), itemCategory.getName(), checked));
		}

		ListView itemcatList = (ListView) findViewById(R.id.edit_item_list_itemcat);
		itemcatList.setAdapter(listEntryCheck_itemCat.Adapter(this, android.R.layout.simple_list_item_1, this.itemCategories));
		itemcatList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parentView, View selectedItemView, int position, long id) {
				ListEntryCheck.EntryRecord itemCategory = itemCategories.get(position);
				if (itemCategory.checked) {
					itemCategory.checked = false;
				} else {
					itemCategory.checked = true;
				}
				itemCategories.set(position, itemCategory);
			}
		});
		itemcatList.setVisibility(View.VISIBLE);

		TextView txt3 = (TextView) findViewById(R.id.edit_item_txt3);
		txt3.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				ListView itemcatList = (ListView) findViewById(R.id.edit_item_list_itemcat);
				if (itemcatList.getVisibility() == View.VISIBLE) {
					itemcatList.setVisibility(View.GONE);
				} else {
					itemcatList.setVisibility(View.VISIBLE);
				}
			}
		});

		// shops
		ListEntryCheck listEntryCheck_shops = new ListEntryCheck(EditItemAct.CHECKLIST_SHOPS, this);
		this.shops = new ArrayList<ListEntryCheck.EntryRecord>();
		for (Shops shop : ShopsDataSource.readAll()) {
			boolean checked = false;
			if (this.selectedItemId != -1) {
				if (Shops_has_ItemsDataSource.read(shop.getId(), this.selectedItemId) != null) {
					checked = true;
				}
			}
			this.shops.add(listEntryCheck_shops.Record(shop.getId(), shop.getName(), checked));
		}

		ListView shopList = (ListView) findViewById(R.id.edit_item_list_shop);
		shopList.setAdapter(listEntryCheck_shops.Adapter(this, android.R.layout.simple_list_item_1, this.shops));
		shopList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parentView, View selectedItemView, int position, long id) {
				ListEntryCheck.EntryRecord shop = shops.get(position);
				if (shop.checked) {
					shop.checked = false;
				} else {
					shop.checked = true;
				}
				shops.set(position, shop);
			}
		});
		shopList.setVisibility(View.VISIBLE);

		TextView txt4 = (TextView) findViewById(R.id.edit_item_txt4);
		txt4.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				ListView itemcatList = (ListView) findViewById(R.id.edit_item_list_shop);
				if (itemcatList.getVisibility() == View.VISIBLE) {
					itemcatList.setVisibility(View.GONE);
				} else {
					itemcatList.setVisibility(View.VISIBLE);
				}
			}
		});

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.edit_action, menu);
		if (this.selectedItemId == -1) {
			MenuItem item = menu.findItem(R.id.mnu_delete);
			item.setEnabled(false);
			item.setVisible(false);
		}
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			onBackPressed();
			break;
		case R.id.mnu_save:
			this.saveChanges();
			break;
		case R.id.mnu_delete:
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle(getText(R.string.are_you_sure));
			builder.setMessage(getText(R.string.delete_item));
			// yes
			builder.setPositiveButton(getText(R.string.yes), new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					// delete items in ItemCategories
					Items_in_ItemCategoriesDataSource.delete(Items_in_ItemCategoriesDataSource.COLUMN_ITEM_ID, EditItemAct.this.selectedItemId);
					// delete items in Shops
					Shops_has_ItemsDataSource.delete(Shops_has_ItemsDataSource.COLUMN_ITEM_ID, EditItemAct.this.selectedItemId);
					// delete item
					ItemsDataSource.delete(new Items(EditItemAct.this.selectedItemId));
					dialog.dismiss();
					Intent intent = new Intent();
					intent.putExtra("dataChanged", true);
					setResult(RESULT_OK, intent);
					finish();
				}
			});
			// no
			builder.setNegativeButton(getText(R.string.no), new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			});
			AlertDialog alert = builder.create();
			alert.show();
			break;
		default:
			return super.onOptionsItemSelected(item);
		}
		return true;
	}

	private void saveChanges() {
		EditText edt_name = (EditText) findViewById(R.id.edit_shop_edt_name);
		if (edt_name.getText().toString().matches("")) {
			Toast.makeText(this, R.string.required_insert_name, Toast.LENGTH_LONG).show();
		} else {
			Items foundItem = ItemsDataSource.read(ItemsDataSource.COLUMN_NAME + " = ?", new String[] { edt_name.getText().toString() });
			// save
			if ((foundItem == null) || (this.selectedItemId == foundItem.getId())) {
				EditText edt_desc = (EditText) findViewById(R.id.edit_item_edt_desc);
				if (foundItem == null) {
					foundItem = new Items(this.selectedItemId);
				}
				foundItem.setName(edt_name.getText().toString());
				foundItem.setDescription(edt_desc.getText().toString());
				ItemsDataSource.save(foundItem);
				// save Items_in_ItemCategories
				for (ListEntryCheck.EntryRecord itemCategory : this.itemCategories) {
					// check if exists
					Items_in_ItemCategories items_in_ItemCategories = Items_in_ItemCategoriesDataSource.read(itemCategory.id, foundItem.getId());
					if (itemCategory.checked) {
						// checked and not in database
						if (items_in_ItemCategories == null) {
							Items_in_ItemCategoriesDataSource.save(new Items_in_ItemCategories(foundItem.getId(), itemCategory.id));
						}
					} else {
						// unchecked and in database
						if (items_in_ItemCategories != null) {
							Items_in_ItemCategoriesDataSource.delete(items_in_ItemCategories);
						}
					}
				}
				// save shops
				for (ListEntryCheck.EntryRecord shop : this.shops) {
					// check if exists
					Shops_has_Items shops_has_Items = Shops_has_ItemsDataSource.read(shop.id, foundItem.getId());
					if (shop.checked) {
						// checked and not in database
						if (shops_has_Items == null) {
							Shops_has_ItemsDataSource.save(new Shops_has_Items(shop.id, foundItem.getId()));
						}
					} else {
						// unchecked and in database
						if (shops_has_Items != null) {
							Shops_has_ItemsDataSource.delete(shops_has_Items);
						}
					}
				}
				// return data changed flag
				Intent intent = new Intent();
				intent.putExtra("dataChanged", true);
				setResult(RESULT_OK, intent);
				finish();
				// duplicate name
			} else {
				Toast.makeText(this, R.string.duplicate_entry, Toast.LENGTH_LONG).show();
			}
		}
	}

	@Override
	public void onCheckClick(int actionId, int id, boolean isChecked) {
		int index = -1;
		switch (actionId) {
		case EditItemAct.CHECKLIST_ITEMCAT:
			for (ListEntryCheck.EntryRecord itemCategory : this.itemCategories) {
				index++;
				if (itemCategory.id == id) {
					itemCategory.checked = isChecked;
					this.itemCategories.set(index, itemCategory);
					break;
				}
			}
			break;
		case EditItemAct.CHECKLIST_SHOPS:
			for (ListEntryCheck.EntryRecord shop : this.shops) {
				index++;
				if (shop.id == id) {
					shop.checked = isChecked;
					this.shops.set(index, shop);
					break;
				}
			}
			break;
		}

	}

}
